//
//  Network.m
//  kronborg
//
//  Created by Jonas Jongejan on 19/08/10.
//  Copyright 2010 HalfdanJ. All rights reserved.
//

#import "Network.h"


@implementation Network

+(void) initializeNetwork:(id)delegateObject type:(NSString*)type name:(NSString*)name {
	
	NSSocketPort *socket;
	NSNetService *service;
	struct sockaddr *addr;
	int port;
	
	socket = [[NSSocketPort alloc] init];// 1
	if(socket)
	{
		//[self setUpSocket:socket];// 2
		
		addr = (struct sockaddr *)[[socket address] bytes];// 3
		if(addr->sa_family == AF_INET)
		{
			port = ntohs(((struct sockaddr_in *)addr)->sin_port);
		}
		else if(addr->sa_family == AF_INET6)
		{
			port = ntohs(((struct sockaddr_in6 *)addr)->sin6_port);
		}
		else
		{
			[socket release];
			socket = nil;
			NSLog(@"The family is neither IPv4 nor IPv6. Can't handle.");
		}
	}
	else
	{
		NSLog(@"An error occurred initializing the NSSocketPort object.");
	}
	
	if(socket)
	{
		service = [[NSNetService alloc] initWithDomain:@""// 4
												  type:type
												  name:name port:port];
		if(service)
		{
			[service setDelegate:delegateObject];// 5
			[service publish];// 6
		}
		else
		{
			NSLog(@"An error occurred initializing the NSNetService object.");
		}
	}
	else
	{
		NSLog(@"An error occurred initializing the NSSocketPort object.");
	}
}


+(void)startBrowsing:(id)delegateObject type:(NSString*)type{
	NSNetServiceBrowser *serviceBrowser;
	
	serviceBrowser = [[NSNetServiceBrowser alloc] init];
	[serviceBrowser setDelegate:delegateObject];
	[serviceBrowser searchForServicesOfType:type inDomain:@""];
}

+(void) resolveService:(id)delegateObject named:(NSString*)serviceName type:(NSString*)type{
	NSNetService *service;
	
	service = [[[NSNetService alloc] initWithDomain:@"local." type:type name:serviceName] retain];
	NSLog(@"Service to resolve: %@",service);
	[service setDelegate:delegateObject];
	[service resolveWithTimeout:5.0];
}

@end
